package upload.upload;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import upload.storage.StorageFileNotFoundException;
import upload.storage.StorageService;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * Created by utstarcom on 2017/2/9.
 */
@Controller
public class FileUploadController {
    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/upload")
    public String listUploadedFiles(Model model) throws IOException {

        model.addAttribute("files", storageService
                .loadAll()
                .map(path ->
                        MvcUriComponentsBuilder
                                .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                                .build().toString())
                .collect(Collectors.toList()));

        return "uploadForm";
    }

    @GetMapping("/upload/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity
                .ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                .body(file);
    }

//    @RequestMapping("/upload")
//    public String handleFileUpload(@RequestParam("file") MultipartFile file,
//                                   RedirectAttributes redirectAttributes) {
//
//        storageService.store(file);
//        redirectAttributes.addFlashAttribute("message",
//                "You successfully uploaded " + file.getOriginalFilename() + "!");
//
//        return "redirect:/";
//    }

    @RequestMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        storageService.store(file);
        return "redirect:/";
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }

//    /**
//     * 多文件上传
//     *
//     * @throws IllegalStateException
//     * @throws IOException
//     */
//    @RequestMapping(value = "/upload/multi_files")
//    public String multiUpload(@RequestParam("files") MultipartFile[] files)
//            throws IOException {
//        //遍历并保存文件
//        for (MultipartFile file : files) {
//            String path = "E:/" + new Date().getTime() + "_" + file.getOriginalFilename();
//
//            File newFile = new File(path);
//            //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
//            file.transferTo(newFile);
//        }
//        return "redirect:uploadPage";
//    }

//    /*
//     * 采用file.Transto 来保存上传的文件
//     */
//    @RequestMapping("/upload/sign_file")
//    public String fileUpload2(@RequestParam("file") MultipartFile file) throws IOException {
////        storageService.store(file);
//        long startTime = System.currentTimeMillis();
//        System.out.println("fileName：" + file.getOriginalFilename());
//        String path = "E:/" + new Date().getTime() + "_" + file.getOriginalFilename();
//
//        File newFile = new File(path);
//        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
//        file.transferTo(newFile);
//        long endTime = System.currentTimeMillis();
//        System.out.println("方法二的运行时间：" + String.valueOf(endTime - startTime) + "ms");
//        return "redirect:/";
//    }
}
